//
//  DPNLoadingView.m
//  Dolphin
//
//  Created by YaoZhaofeng on 16/5/11.
//  Copyright © 2016年 JJ. All rights reserved.
//

#import "RNLoadingView.h"

//static const CGFloat kImageWidth = 150.0f;
//static const CGFloat kTopPadding = 150.0f;
//static const CGFloat kMiddlePadding = 30.0f;
//
//static const CGFloat kFPS = 30.0f;
//static const CGFloat kImageRotateAngle = 2*M_PI/kFPS;
//static const NSTimeInterval kImageRotateInterval = 1/kFPS;
static const NSTimeInterval kDisappearInterval = 0.5f;

RNLoadingView *loadingView = nil;
dispatch_block_t showBtnBlock;

@interface RNLoadingView ()
//@property (nonatomic, strong) UIImageView *loadingImageView;
//@property (nonatomic, strong) UIImageView *dolphinImageView;
@property (nonatomic, strong) UIButton *backBtn;
@end

@implementation RNLoadingView

- (void)dealloc {
    NSLog(@"dealloc");
}

- (id)init {
    return [self initWithFrame:CGRectZero];
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
//        self.backgroundColor = [UIColor redColor];
        //version0
//        UIImageView * bgView = [[UIImageView alloc]initWithImage:GetImage(@"bg_loading")];
//        bgView.frame = frame;
//        [self addSubview:bgView];
//
//        _loadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-kImageWidth)/2, kTopPadding, kImageWidth, kImageWidth)];
//        _loadingImageView.image = GetImage(@"loading_progress_0");
//        [self addSubview:_loadingImageView];
//
//        _dolphinImageView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-kImageWidth)/2, kTopPadding, kImageWidth, kImageWidth)];
//        _dolphinImageView.image = GetImage(@"dolphin_1");
//
//        [self addSubview:_dolphinImageView];
//
//        UILabel *tipLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_loadingImageView.frame)+kMiddlePadding, SCREEN_WIDTH, 25)];
//        tipLbl.textAlignment = NSTextAlignmentCenter;
//        tipLbl.font = GetFont(18);
//        tipLbl.textColor = [UIColor whiteColor];
//        tipLbl.text = @"小海豚正在努力加载...";
//        [self addSubview:tipLbl];
//
//        [self updateImages];
        
//        UIImageView * bgView = [[UIImageView alloc]initWithImage:GetImage(@"portrait_bg.jpg")];
        self.layer.contents = (id)GetImage(@"portrait_bg.jpg").CGImage;
//        bgView.frame = frame;
//        [self addSubview:bgView];
        
        UIImageView *iconImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, 360, 340)];
        CGPoint center = iconImage.center;
        center.x = self.center.x;
        iconImage.center = center;
//        iconImage.image = GetImage(@"protrait_bg_logo");
        iconImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://webcloudplt.srv.jj.cn/0/upload/3025/cloudcmsExt/picture/ad720276ba3ca6a6_73223_240x240.png"]]];
        [self addSubview:iconImage];
        
        UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(frame) - 76 - 53, 143, 53)];
        center = backBtn.center;
        center.x = self.center.x;
        backBtn.center = center;
        [backBtn setBackgroundImage:GetImage(@"button_back") forState:UIControlStateNormal];
        [backBtn setBackgroundImage:GetImage(@"button_back_press") forState:UIControlStateHighlighted];
        backBtn.hidden = YES;
        [backBtn addTarget:self action:@selector(backBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:backBtn];
        _backBtn = backBtn;
        
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [activityView setCenter:CGPointMake(self.center.x, backBtn.center.y - 75)];
        [activityView startAnimating];
        [self addSubview:activityView];
    }
    
    return self;
}

- (id)initWithFrame:(CGRect)frame bgImg:(NSString*)bgImgs {
    if (self = [super initWithFrame:frame]) {
        UIImage* myImage = [UIImage imageWithContentsOfFile:bgImgs];
        UIImageView * bgView = [[UIImageView alloc] initWithImage: myImage];
        bgView.contentMode = UIViewContentModeScaleAspectFit;
        bgView.frame = frame;
        bgView.transform = CGAffineTransformMakeRotation(M_PI_2);//翻转角度
        bgView.center = CGPointMake(frame.size.height/2, frame.size.width/2);
        [self addSubview:bgView];
    }
    return self;
}

/*version0
- (void)updateImages {
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:kImageRotateInterval animations:^{
        CGAffineTransform currentTransform = _loadingImageView.transform;
        CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform, kImageRotateAngle); // 在现在的基础上旋转指定角度
        _loadingImageView.transform = newTransform;
    } completion:^(BOOL finished) {
        [weakSelf performSelector:@selector(updateImages)];
    }];
}*/

- (void)showBackBtn {
    [_backBtn setHidden:NO];
}

- (void)backBtnClicked:(id)sender {
    [RNLoadingView hide];
}

#pragma mark - class method

+ (void)show {
    if (loadingView) {
        [loadingView removeFromSuperview];
        loadingView = nil;
    }
    showBtnBlock = dispatch_block_create(0, ^{
        if (loadingView) {
            [loadingView showBackBtn];
        }
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0f * NSEC_PER_SEC), dispatch_get_main_queue(), showBtnBlock);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2.0f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [RNLoadingView hide];
    });
    loadingView = [[RNLoadingView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    CGSize screenSize = [UIScreen mainScreen].nativeBounds.size;
    BOOL isIphoneX = RCTIsIPhoneX();
    NSLog(@"isIphoneX :: %d,, screenSize:: %@", isIphoneX, NSStringFromCGSize(screenSize));
    [[[UIApplication sharedApplication] keyWindow] addSubview:loadingView];
    
}

+ (void)showJJLive:(NSString*)bgImg{
    if (loadingView) {
        [loadingView removeFromSuperview];
        loadingView = nil;
    }
    loadingView = [[RNLoadingView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width) bgImg:bgImg];
    [[[UIApplication sharedApplication] keyWindow] addSubview:loadingView];
    
    //防止一直loading的异常，添加一个超时机制
    dispatch_block_t delayed_block = ^{
        [RNLoadingView hide];
    };
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 8.0f * NSEC_PER_SEC), dispatch_get_main_queue(), delayed_block);
}

+ (void)hide {
    if (loadingView) {
        [UIView animateWithDuration:kDisappearInterval animations:^{
            loadingView.alpha = 0.0f;
        } completion:^(BOOL finished) {
            if (showBtnBlock) {
                dispatch_block_cancel(showBtnBlock);
                showBtnBlock = nil;
            }
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

static BOOL RCTIsIPhoneX() {
    static BOOL isIPhoneX = NO;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        CGSize screenSize = [UIScreen mainScreen].nativeBounds.size;
        CGSize iPhoneXScreenSize = CGSizeMake(1125, 2436);
        CGSize iPhoneXMaxScreenSize = CGSizeMake(1242, 2688);
        CGSize iPhoneXRScreenSize = CGSizeMake(828, 1792);
        
        isIPhoneX =
        CGSizeEqualToSize(screenSize, iPhoneXScreenSize) ||
        CGSizeEqualToSize(screenSize, iPhoneXMaxScreenSize) ||
        CGSizeEqualToSize(screenSize, iPhoneXRScreenSize);
    });
    
    return isIPhoneX;
}

@end
